package com.ht.medicaltreatment.view

import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.PopupWindow
import android.widget.RadioButton
import android.widget.RadioGroup
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.button.MaterialButton
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.bean.BloodDataBean
import com.ht.medicaltreatment.utils.backgroundAlpha

class BloodItemPop(context:Context):PopupWindow(context) {
    private val view: View
    private var onClick:(String,Int) -> Unit = {name,id ->}
    private val radioGroup:RadioGroup
    private val btnNext:MaterialButton
    private val context = context
    private var checkName = ""
    private var checkId = -1

    init {
        view =
            LayoutInflater.from(context).inflate(R.layout.pop_blood_item_layout, null, false)
        contentView = view
        isOutsideTouchable = true
        setBackgroundDrawable(BitmapDrawable())
        isTouchable = true
        width = WindowManager.LayoutParams.MATCH_PARENT
        height = ScreenUtils.getScreenHeight()/2
        animationStyle = R.style.itemPopStyle
        radioGroup = view.findViewById(R.id.radioGroup)
        btnNext = view.findViewById(R.id.btnNext)
        setOnDismissListener {
            ActivityUtils.getTopActivity().backgroundAlpha(1.0f)
        }
        radioGroup.setOnCheckedChangeListener { group, checkedId ->

        }
        //确定
        btnNext.setOnClickListener {
            if(checkId == -1)return@setOnClickListener
            onClick(checkName,checkId)
            dismiss()
        }
    }

    fun setData(items:MutableList<BloodDataBean>):BloodItemPop{
        radioGroup.removeAllViews()
        items.forEach {
            val radioButton = RadioButton(context)
            val params = RadioGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            radioButton.layoutParams = params
            radioButton.setText(it.name)
            radioButton.setTag(it.id)
            radioGroup.addView(radioButton)
            radioButton.setOnClickListener {
                checkName = (it as RadioButton).text.toString()
                checkId = it.tag as Int
            }
        }
        return this
    }

    fun show(onClick:(String,Int)->Unit){
        if(radioGroup.childCount == 0){
            ToastUtils.showShort("请调用setData方法设置数据")
            return
        }
        if(isShowing){
            return
        }
        this.onClick = onClick
        ActivityUtils.getTopActivity().backgroundAlpha(0.4f)
        showAtLocation(view, Gravity.BOTTOM,0,0)
    }

}